home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 10208 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.4 KB  |  57 lines

  1. Path: wapping.ecs.soton.ac.uk!tl93
  2. From: tl93@ecs.soton.ac.uk (Tony Lofthouse)
  3. Newsgroups: comp.lang.c++
  4. Subject: A template question...
  5. Date: 6 Mar 1996 17:57:57 GMT
  6. Organization: Electronics and Computer Science, University of Southampton
  7. Message-ID: <4hkjn5$mp1@wapping.ecs.soton.ac.uk>
  8. NNTP-Posting-Host: avon.ecs.soton.ac.uk
  9. X-Newsreader: NN version 6.5.0 (NOV)
  10.  
  11. I want a generic function to perform a sort on an array, so I do the 
  12. following:
  13.  
  14. template <class T>
  15. void mysort(const T* anArray, unsigned arraysize) {
  16.     // implementation   stuff
  17. }
  18.  
  19. o.k. fine. But I also want to pass a pointer to a predicate function which
  20. does the comparasion of elements in the array. It seems to me that this 
  21. predicate function needs to be a template function as well:
  22.  
  23. template <class T>
  24. unsigned greaterthan(const T& x, const T& y) {
  25.     return x > y;
  26. }
  27.  
  28. so my implementation of mysort is:
  29.  
  30.  
  31. template<class T>
  32. void mysort(const  T* anArray, unsigned arraylen,
  33.             unsigned (*predicate) (const T&, constT&)) {
  34.  
  35.     // sort stuff
  36.     if(predicate( el1, el2 ) {
  37.     
  38.     // ----    
  39.     
  40.     }
  41.     //more sort stuff
  42.  
  43. }
  44.  
  45. Unfortunately when I do:
  46.  
  47. extern int* anArray;
  48. extern unsigned anArrayLength;
  49.  
  50. mysort(anArray, anArrayLength, &greaterthan);
  51.  
  52. The compiler fails to match the instantiated mysort to the implemented 
  53. mysort. What's going wrong?? And, how can I fix it?  Any help would  be 
  54. deeply appreciated.
  55.  
  56. Tony
  57.